<template>
  <el-dialog :visible="showVisible" center :show-close="false" width="600px">
    <div class="b g3 f16 tl" slot="title">
      <div class="ks-row-between pl15 pr15">
        <span>{{ isNew ? $t("sys.new_scheduled_task") : $t("sys.edit_scheduled_task") }}</span>
        <span class="el-icon-close g9 f26 poi" @click="handleCancel"></span>
      </div>
    </div>

    <el-form
      class="pl30 pr30"
      :model="formData"
      :disabled="isView"
      ref="form"
      label-width="140px"
    >
      <el-form-item
        :label="$t('sys.task_name')"
        prop="jobName"
        :rules="[
          { required: true, message: $t('sys.task_name_not_null'), trigger: 'change' },
        ]"
      >
        <el-input
          v-model="formData.jobName"
          style="width: 400px"
          :placeholder="$t('sys.enter_task_name')"
          :maxlength="64"
          show-word-limit
        />
      </el-form-item>

      <el-form-item
        :label="$t('sys.cron_expressions')"
        prop="cronExpression"
        :rules="[
          { required: true, message: $t('sys.cron_expressions_not_null'), trigger: 'change' },
        ]"
      >
        <div style="width: 400px; display: flex; align-items: center">
          <el-input
            class="mr10"
            v-model="formData.cronExpression"
            :placeholder="$t('sys.enter_cron_expressions')"
            :maxlength="200"
            show-word-limit
          />
          <el-button type="text" @click="handleCronEdit">{{$t('sys.generate_expression')}}</el-button>
        </div>
      </el-form-item>

      <el-form-item
        :label="$t('sys.select_script')"
        prop="scriptId"
        :rules="[{ required: true, message: $t('sys.enter_select_script'), trigger: 'change' }]"
      >
        <tree-select
          v-model="formData.scriptId"
          style="width: 400px"
          filterable
          :fieldMap="{
            value: 'id',
            label: 'name',
            disabled: 'disabled',
          }"
          :filterNodeMethod="filterNodeMethod"
          :treeData="scriptList"
        />
      </el-form-item>
      <el-form-item
        :label="$t('sys.default_state')"
        prop="status"
        :rules="[
          { required: true, message: $t('sys.default_state_not_null'), trigger: 'change' },
        ]"
      >
        <el-select
          style="width: 400px"
          clearable
          v-model="formData.status"
          filterable
        >
          <el-option
            v-for="item in TASK_STATUS_ENUM"
            :key="item.label"
            :value="item.value"
            :label="$t('sys.' + item.i18nLable)"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        :label="$t('sys.enforce_record_retention_rules')"
        prop="logKeepType"
        :rules="[
          { required: true, message: $t('sys.set_retention_rules'), trigger: 'change' },
        ]"
      >
        <el-select
          v-model="formData.logKeepType"
          style="width: 240px"
          :placeholder="$t('sys.please_select')"
          @change="handleRuleChange"
        >
          <el-option
            v-for="(value, key) in logTypeEnum"
            :key="key"
            :value="key"
            :label="value"
          />
        </el-select>
        <el-form-item
          prop="logKeepValue"
          style="display: inline-block; margin-left: 5px; margin-right: 10px"
          label-width="0px"
        >
          <el-input-number
            v-model="formData.logKeepValue"
            controls-position="right"
            :min="1"
          >
          </el-input-number>
        </el-form-item>

        <span v-if="formData.logKeepType === 'COUNT'">{{$t('sys.strip')}}</span>
        <span v-if="formData.logKeepType === 'DAYS'">{{$t('sys.days')}}</span>
      </el-form-item>
    </el-form>

    <div slot="footer" class="tr">
      <el-button v-if="!isView" @click="handleCancel">{{$t('sys.cancel')}}</el-button>
      <el-button v-if="!isView" type="primary" @click="submit">{{$t('sys.confirm')}}</el-button>
      <el-button v-if="isView" type="primary" @click="handleCancel"
        >{{$t('sys.close')}}</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import i18n from '../../../../../i18n'
import CronModal from "@/components/CronModal";
import {
  createScriptTreeNode,
  filterNodeMethod,
} from "@/utils/treeSelectFormat";
import { postHmjob,putHmjob } from '@/apis/paas/HmJobController.js'
import { getHmscriptfolderListTree } from '@/apis/paas/HmScriptFolderController.js'
import { TASK_STATUS_ENUM } from "@/utils/enum";
const logTypeEnum = {
  DAYS: i18n.t("sys.by_time"),
  COUNT: i18n.t("sys.by_number_records"),
};
export default {
  name: "JobForm",
  data() {
    return {
      logTypeEnum,
      TASK_STATUS_ENUM,
      filterNodeMethod,
      showVisible: false,
      isView: false,
      formData: {},
      scriptList: [],
      scriptLoading: false,
    };
  },

  computed: {
    isNew() {
      return !this.formData.jobId;
    },
  },

  watch: {
    showVisible(val) {
      if (val) {
        getHmscriptfolderListTree().then((res) => {
          res.forEach((node) => {
            node.type = "folder";
          });
          this.scriptList = createScriptTreeNode(res || []);
        });
      }
    },
  },

  created() {},

  methods: {
    addForm(record = {}) {
      this.showVisible = true;
      this.formData = {
        ...record,
        status: TASK_STATUS_ENUM[0].value,
        logKeepType: "COUNT",
        logKeepValue: 100,
      };
      this.fileData = {};
      this.codeData = {};
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },

    editForm(record = {}) {
      this.showVisible = true;
      this.formData = {
        ...record,
      };
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },
    viewForm(record = {}) {
      this.showVisible = true;
      this.isView = true;
      this.formData = {
        ...record,
      };
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },

    handleCronEdit() {
      CronModal.open(
        {
          title: this.$t("sys.cron_expressions"),
          value: this.formData.cronExpression,
        },
        (res) => {
          this.$set(this.formData, "cronExpression", res);
        }
      );
    },

    async submit() {
      try {
        await this.$refs.form.validate();
        const {
          jobId,
          jobName,
          cronExpression,
          scriptId,
          status,
          logKeepType,
          logKeepValue,
        } = this.formData;
        let params = {};
        let request = null;
        if (this.isNew) {
          params = {
            jobName,
            cronExpression,
            scriptId,
            status,
            logKeepType,
            logKeepValue,
          };
          request = postHmjob;
        } else {
          params = {
            jobId,
            jobName,
            cronExpression,
            scriptId,
            status,
            logKeepType,
            logKeepValue,
          };
          request = putHmjob;
        }
        for (const key in params) {
          params[key] =
            typeof params[key] === "string" ? params[key].trim() : params[key];
        }
        request(params).then((res) => {
          this.handleCancel();
          this.$emit("ok");
        });
      } catch (error) {
        console.log(error);
      }
    },
    handleRuleChange(val) {
      if (val === "COUNT") {
        this.formData.logKeepValue = 100;
      } else {
        this.formData.logKeepValue = null;
      }
    },
    handleCancel() {
      this.showVisible = false;
      this.isView = false;
    },
  },
};
</script>

<style lang="scss" scoped>
</style>
